package com.example.onion.hxchat.util;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * 获得环信的token
 * @author:onion
 * @data: 2020/5/20
 */
public class HXUtils {

    public static String getToken(String url1)
            throws Exception {
        String resultStr = null;
        //@SuppressWarnings("resource")
        //DefaultHttpClient httpClient = new DefaultHttpClient();
//        URL url = new URL(url1);
//        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//        connection.setRequestMethod("POST");
        //首先创建一个okhttp实例
        OkHttpClient client = new OkHttpClient();
        //要发起请求，创建一个request对象(GET)
//        Request request = new Request.Builder()
//                         .url(url1)
//                         .build();
        //POST，发起post请求，需要构建一个requestBody对象存放待提交的参数
        RequestBody requestBody = new FormBody.Builder()
                .add("grant_type","client_credentials")
                .add("client_id","YXA6KqReQKvhQT-Uc9Kvh9xN5A")
                .add("client_secret","YXA6NVGh2rNKqdvWvAZ4BkwBOcDuCwY")
                .build();
        Request request = new Request.Builder()
                .url(url1)
                .post(requestBody)
                .addHeader("Content-Type","application/json")
                .addHeader("Accept","application/json")
                .post(requestBody)
                .build();
        //Get POST 发送请求并获取数据
        Response response = client.newCall(request).execute();
        //Respnse对象就是服务器返回的数据了  可以这样得到
        String responseData = response.body().string();
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(responseData,JsonObject.class);

        return jsonObject.get("access_token").toString();
    }
}
